import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {HttpService} from '../../service/http.service';
import {Title} from "@angular/platform-browser";

@Component({
  selector: 'app-sort',
  templateUrl: './sort.component.html',
  styleUrls: ['./sort.component.css']
})
export class SortComponent implements OnInit {

  categoryId: number;
  categoryName: string;
  weight = 0;
  projectSortList = null;

  constructor(private route: ActivatedRoute,
              private titleService: Title,
              private httpService: HttpService) {
  }

  ngOnInit(): void {
    this.route.params
      .subscribe(params => {
        this.categoryId = +params['id'];
        this.categoryName = params['name'];
        this.titleService.setTitle(this.categoryName + '加盟_' + this.categoryName + '加盟连锁品牌_315加盟网' );
      });
    this.getCategoryProjectList();
  }

  getCategoryProjectList() {
    this.httpService.getCategoryProjectList(this.categoryId, this.weight).then(r => {
      if (r.length > 0) {
        for (let i = 0; i < r.length; i++) {
          const buff: string[] = (r[i].major).split(' ');
          for (let j = 0; j < buff.length; j++) {
            if (buff[j].length < 2) {
              buff.splice(j, 1);
            }
          }
          r[i].majors = buff;
        }
        console.log(r);
        this.changeEndWeight(r[(r.length - 1)].weight);
        if (this.projectSortList === null) {
          this.projectSortList = r;
        } else {
          this.projectSortList = this.projectSortList.concat(r);
        }
      }
      console.log(this.projectSortList);
    });
  }

  changeEndWeight(weight) {
    this.weight = weight;
  }

  onScroll() {
    if (this.projectSortList.length % 20 === 0) {
      console.log('scrolled down!!');
      this.getCategoryProjectList();
    }
  }

}
